#include "bulletList.h"

using namespace std;

BulletList::BulletList() {
}

BulletList::BulletList(Image bulletImage) {
	bulletList = vector<Bullet>();
	repurposeStack = vector<int>();
	this->bulletImage = bulletImage;
}

BulletList::~BulletList() {
}

void BulletList::addNewBullet(float x, float y, float playerPosX, float playerPosY) {
	float bulletStartX = x;
	float bulletStartY = y;

	float magnitude = (playerPosX - bulletStartX) * (playerPosX - bulletStartX)
						+ (playerPosY - bulletStartY) * (playerPosY - bulletStartY);
	float ratio = sqrt(BULLET_SPEED * BULLET_SPEED / magnitude);
	float velX = (playerPosX - bulletStartX) * ratio;
	float velY = (playerPosY - bulletStartY) * ratio;

	if (repurposeStack.size() > 0) {
		int i = repurposeStack.back();
		repurposeStack.pop_back();
		bulletList[i].setPosX(bulletStartX);
		bulletList[i].setPosY(bulletStartY);
		bulletList[i].setVelX(velX);
		bulletList[i].setVelY(velY);
	}
	else {
		Bullet newBullet(bulletImage,bulletStartX,bulletStartY,velX,velY);
		bulletList.push_back(newBullet);
	}
}

vector<Bullet> BulletList::moveBullets(float frameTime, float characterPosX, float characterPosY) {
	int i = 0;
	vector<Bullet> nearBullets = vector<Bullet>();
	for (auto it = bulletList.begin(); it != bulletList.end(); ++it) {
		it->update(frameTime);
		float xdist = characterPosX - it->getPosX();
		float ydist = characterPosY - it->getPosY();
		if (it->isOutOfBounds() && !contains(repurposeStack, i)) {
			repurposeStack.push_back(i);
		}
		else if (xdist < PLAYER_WIDTH || ydist < PLAYER_WIDTH) {
			nearBullets.push_back((*it));
		}
		i++;
	}
	return nearBullets;
}

void BulletList::draw() {
	for (auto it = bulletList.begin(); it != bulletList.end(); ++it) {
		it->draw();
	}
}

bool BulletList::contains(vector<int> vec, int i) {
	for (auto it = vec.begin(); it != vec.end(); ++it) {
		if ((*it) == i) {
			return true;
		}
	}
	return false;
}